<template>
	<view>
		<view class="notice-page">
		    <!-- 标签栏 -->
		    <view class="tab-bar">
		      <view class="tab-item" 
		        :class="{ active: currentTab === 'unread' }"
		        @click="switchTab('unread')"
		      >
		        <text>未读</text>
		        <view class="badge" v-if="unreadCount > 0">{{ unreadCount }}</view>
		      </view>
		      <view 
		        class="tab-item" 
		        :class="{ active: currentTab === 'read' }"
		        @click="switchTab('read')"
		      >
		        <text>已读</text>
		      </view>
		    </view>
		    
		    <!-- 通知内容区域 -->
		    <view class="notice-content">
		      <view v-if="currentMessageList.length === 0" class="empty-state">
		        <text class="empty-text">{{ currentTab === 'unread' ? '暂无未读消息' : '暂无已读消息' }}</text>
		      </view>
		      
		      <view 
		        v-for="(item, index) in currentMessageList" 
		        :key="item.id"
		        class="notice-item"
		        :class="{ unread: !item.isRead }"
		        @click="markAsRead(item, index)"
		      >
		        <view class="notice-header">
		          <text class="notice-title">{{ item.title }}</text>
		          <view class="unread-dot" v-if="!item.isRead"></view>
		        </view>
		        <text class="notice-desc">{{ item.content }}</text>
		        <text class="notice-time">{{ item.time }}</text>
		      </view>
		    </view>
		  </view>
	</view>
</template>

<script>
	import {get,put} from '@/config/request.js'
	export default {
		data() {
			return {
				currentTab: 'unread',
				messageList: [],
				memberId: null
			}
		},
		computed: {
			// 根据当前tab筛选消息列表
			currentMessageList() {
				if (this.currentTab === 'unread') {
					return this.messageList.filter(item => !item.isRead);
				} else {
					return this.messageList.filter(item => item.isRead);
				}
			},
			// 未读消息数量
			unreadCount() {
				return this.messageList.filter(item => !item.isRead).length;
			}
		},
		methods: {
			// 获取消息信息
			async getInform(){
				try {
					// 获取用户ID
					let userId = null;
					
					// 方法1: 从userInfo获取用户ID（根据登录页面的存储方式）
					const userInfo = uni.getStorageSync('userInfo');
					console.log('从userInfo获取:', userInfo);
					if (userInfo && userInfo.memberId) {
						userId = userInfo.memberId;
						console.log('从userInfo.id获取用户ID:', userId);
					}			
					if (!userId) {				
						console.error('未找到用户ID');
						uni.showToast({
							title: '请先登录',
							icon: 'none',
							duration: 2000
						});
						return;
					}
					
					console.log('当前用户ID:', userId);
					
					// 构建请求参数
					const params = {
						pageNum: 1,
						pageSize: 10,
						userId: userId  // 添加用户ID参数
					};
					
					// 请求通知列表
					const res = await get('/message/inform/list', params);
					console.log('通知数据:', res);
					
					if (res && res.code === 200) {
						// 处理返回的通知数据
						if (res.rows && res.rows.length > 0) {
							this.messageList = res.rows.map(item => ({
								id: item.id || item.messageId,
								title: item.title || item.messageTitle || '系统通知',
								content: item.content || item.messageContent || item.description || '',
								time: item.createTime || item.sendTime || item.time || new Date().toLocaleString(),
								isRead: item.isRead || item.readStatus === 1 || false
							}));
						} else {
							this.messageList = [];
						}
						
						console.log('处理后的通知列表:', this.messageList);
					} else {
						console.error('获取通知失败:', res);
						uni.showToast({
							title: '获取通知失败',
							icon: 'none',
							duration: 2000
						});
					}
					
				} catch (error) {
					console.error('获取通知信息失败:', error);
					uni.showToast({
						title: '获取通知失败',
						icon: 'none',
						duration: 2000
					});
				}
			},
			// 切换标签
			switchTab(tab) {
				this.currentTab = tab;
			},
			
			// 标记消息为已读
			async markAsRead(item, index) {
				console.log("点击的消息的ID：" + item.id);
				
				if (!item.isRead) {
					try {
						const updateparams = {
							id: item.id,
							title: item.title,
							content: item.content,
							time: item.createTime, 
							isRead: 1
						};
						
						console.log('更新消息状态参数:', updateparams);
						
						// 调用服务端API更新消息状态
						const res = await put('/message/inform/', updateparams);
						console.log("修改消息状态的结果：", res);
						
						if (res && res.code === 200) {
							// 更新本地消息状态 - 这是关键！
							item.isRead = true;
							
							// 显示提示
							uni.showToast({
								title: '已标记为已读',
								icon: 'success',
								duration: 1500
							});
							
							// 如果当前在未读页面且没有未读消息了，自动切换到已读页面
							if (this.currentTab === 'unread' && this.unreadCount === 0) {
								setTimeout(() => {
									this.currentTab = 'read';
									uni.showToast({
										title: '已自动切换到已读页面',
										icon: 'none',
										duration: 2000
									});
								}, 1500);
							}
							
							// 更新首页未读消息数量
							this.updateHomePageUnreadCount();
							
						} else {
							console.error('更新消息状态失败:', res);
							uni.showToast({
								title: '更新失败，请重试',
								icon: 'none',
								duration: 2000
							});
						}
						
					} catch (error) {
						console.error('更新消息状态出错:', error);
						uni.showToast({
							title: '更新失败，请重试',
							icon: 'none',
							duration: 2000
						});
					}
				}
			},
			
			// 更新首页未读消息数量
			updateHomePageUnreadCount() {
				const pages = getCurrentPages();
				const homePage = pages.find(page => page.route === 'pages/index/index');
				if (homePage) {
					homePage.updateUnreadCount(this.unreadCount);
				}
			}
		},
		onLoad() {
			console.log('消息页面加载完成');
			// 加载通知数据
			this.getInform();
		},
		onShow() {
			// 页面显示时更新首页的未读消息数量
			this.updateHomePageUnreadCount();
		},
		onHide() {
			// 页面隐藏时更新首页的未读消息数量
			this.updateHomePageUnreadCount();
		}
	}
</script>

<style>
.notice-page {
  background-color: #fff;
  min-height: 100vh;
}

/* 标签栏样式 */
.tab-bar {
  display: flex;
  border-bottom: 1px solid #eee;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #333;
  position: relative;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #007aff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #007aff;
  border-radius: 2rpx;
}

/* 未读消息数量徽章 */
.badge {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 32rpx;
  text-align: center;
  line-height: 1;
}

/* 通知内容样式 */
.notice-content {
  padding: 20rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}

.notice-item {
  border-bottom: 1px solid #f5f5f5;
  padding: 30rpx 0;
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
  position: relative;
}

.notice-item:active {
  background: #f8f8f8;
  transform: scale(0.98);
}

.notice-item.unread {
  background: rgba(0, 122, 255, 0.05);
  border-radius: 10rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.notice-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.notice-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 15rpx;
  line-height: 1.5;
  display: block;
}

.notice-time {
  font-size: 24rpx;
  color: #999;
  display: block;
}

/* 未读消息红点 */
.unread-dot {
  width: 16rpx;
  height: 16rpx;
  background: #ff4757;
  border-radius: 50%;
  flex-shrink: 0;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .tab-item {
    font-size: 26rpx;
    padding: 15rpx 0;
  }
  
  .notice-title {
    font-size: 28rpx;
  }
  
  .notice-desc {
    font-size: 24rpx;
  }
  
  .notice-time {
    font-size: 22rpx;
  }
}
</style>
